//
//  AddMapViewController.m
//
//  AddMapViewController.m
//  GoBigMarket
//
//  Created by 王天义 on 16/8/18.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "AddMapViewController.h"

#import "TitleSearchViewController.h"


@interface AddMapViewController () <BMKMapViewDelegate, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate>
{
    BMKMapView* mapView;//地图视图
    BMKLocationService *locService; //定位
    
    BMKPointAnnotation *pointAnnotation; // 一开始显示的大头针
    BOOL annotaionShow; // 使大头针仅显示一个
    UIPanGestureRecognizer *mapViewPan;
    BOOL mapPanGestureRecognizer; // 使地图仅在拖动停止时显示周边信息
    
    UIButton *locationBtn; //返回原定位坐标点按钮
    
    UITableView *myTableView;
    NSMutableArray *addressDataArray;
    
    NSString *_latitude; // 最终选择的坐标
    NSString *_longitude; // 最终选择的坐标
    NSString *_address;  // 最终选择的地址
    NSString *_name;     // 最终选择的名称
    NSString *_city;     // 最终选择的城市
    NSString *_district;     // 最终选择的区县
    NSString *_province;     // 最终选择的省份
    NSString *_shotName;       //最终选择的商圈
    NSString *screenAddress; // 筛选重复地址
}

@end

@implementation AddMapViewController

- (void)viewWillAppear:(BOOL)animated
{
    [mapView viewWillAppear];
    mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
- (void)viewWillDisappear:(BOOL)animated
{
    [mapView viewWillDisappear];
    mapView.delegate = nil; // 不用时，置nil
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"寻找地址";
    [self.tabBarController.tabBar setHidden:YES];
    addressDataArray = [NSMutableArray arrayWithCapacity:1];
    mapPanGestureRecognizer = NO;
    
    [self loadBackBtnAndSearchBtn];
    
    [self loadMapView];
    [self loadAddressTableView];
}

#pragma mark - baiduMap
- (void)loadMapView {
    annotaionShow = NO;
    
    mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, XNWindowWidth, XNWindowHeight/2)];
    mapView.zoomLevel =17;
    mapView.logoPosition = BMKLogoPositionRightBottom;
    mapView.userTrackingMode = BMKUserTrackingModeFollow;
    [self.view addSubview:mapView];
    mapViewPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panEd:)];
    [mapView addGestureRecognizer:mapViewPan];
    
    UIImageView *labelImage = [[UIImageView alloc] initWithFrame:CGRectMake((XNWindowWidth-25 )/2, XNWindowHeight/4-33, 25, 33)];
    labelImage.image = [UIImage imageNamed:@"icon_baidu_marker"];
    [mapView addSubview:labelImage];
    
    locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    locationBtn.frame = CGRectMake(10, XNWindowHeight/2-60, 50, 50);
    locationBtn.backgroundColor = [UIColor lightGrayColor];
    [locationBtn setTitle:@"定位" forState:UIControlStateNormal];
    [locationBtn addTarget:self action:@selector(locationBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [mapView addSubview:locationBtn];
    locationBtn.hidden = YES;
    
    // 定位
    locService = [[BMKLocationService alloc]init];
    locService.delegate = self;
    //启动LocationService
    [locService startUserLocationService];
}

// 使屏幕显示坐标回到大头针位置
- (void)locationBtnClick {
    CLLocationCoordinate2D coor;
    coor = pointAnnotation.coordinate;
    
    BMKCoordinateRegion region;
    region.center.latitude  = coor.latitude;
    region.center.longitude = coor.longitude;
    region.span.latitudeDelta  = 0;
    region.span.longitudeDelta = 0;
    [UIView animateWithDuration:1 animations:^{
        mapView.region = region;
    }];
    
}

#pragma mark 百度地图delegate
// 标注大头针
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        return newAnnotationView;
    }
    return nil;
}

// 使地图仅在拖动停止时显示周边信息
- (void)panEd:(UIPanGestureRecognizer *)pan {
    mapPanGestureRecognizer = YES;
    [mapView removeGestureRecognizer:mapViewPan];
}
// 当地图停止拖动时显示周边信息
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    if (!mapPanGestureRecognizer) {
        return;
    }
    
    // 把停止拖动时地图的中心点转换成大头针的经纬度
    BMKCoordinateRegion region = (BMKCoordinateRegion)mapView.region;
    
    //——————————初始化反地理编码类————————————
    //注意：必须先初始化地理编码类
    BMKGeoCodeSearch *_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
    _geoCodeSearch.delegate = self;
    //初始化反地理编码类
    BMKReverseGeoCodeOption *reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    //需要反地理编码的坐标位置
    reverseGeoCodeOption.reverseGeoPoint = CLLocationCoordinate2DMake(region.center.latitude, region.center.longitude);
    // 调用反地址编码方法，让其在代理方法中输出
    BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
    if (!flag) {
        [locService startUserLocationService];
    }
}
#pragma mark - 反地理编码
//- (void)EnGeocode {
//    //初始化检索对象
//    BMKGeoCodeSearch *_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
//    _geoCodeSearch.delegate = self;
//    //初始化反地理编码类
//    BMKReverseGeoCodeOption *reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
//    //需要反地理编码的坐标位置
//    reverseGeoCodeOption.reverseGeoPoint = CLLocationCoordinate2DMake(_longitude.doubleValue, _latitude.doubleValue);
//    // 调用反地址编码方法，让其在代理方法中输出
//    BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
//    if(flag)
//    {
//        NSLog(@"反geo检索发送成功");
//    }
//    else
//    {
//        NSLog(@"反geo检索发送失败");
//    }
//    
//   
//}
// 定位
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [locService stopUserLocationService];
    //    NSLog(@"当前的坐标是: %f,%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    //——————————初始化反地理编码类————————————
    //注意：必须先初始化地理编码类
    BMKGeoCodeSearch *_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
    _geoCodeSearch.delegate = self;
    //初始化反地理编码类
    BMKReverseGeoCodeOption *reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    //需要反地理编码的坐标位置
    reverseGeoCodeOption.reverseGeoPoint = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    // 调用反地址编码方法，让其在代理方法中输出
    BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
    if (!flag) {
        DLog(@"false");
        [locService startUserLocationService];
    }else {
        //        NSLog(@"success");
    }
}
#pragma mark 代理方法返回反地理编码结果
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (result) {
        [addressDataArray removeAllObjects];
        screenAddress = [NSString stringWithFormat:@"%@%@", result.addressDetail.streetName, result.addressDetail.streetNumber];
        
        _address = result.address;
        _name = result.addressDetail.streetName;
        _shotName = result.businessCircle;
        _city = result.addressDetail.city;
        _district = result.addressDetail.district;
        _province = result.addressDetail.province;
        _latitude = [NSString stringWithFormat:@"%f", result.location.latitude];
        _longitude = [NSString stringWithFormat:@"%f", result.location.longitude];
        
        NSDictionary *dic = @{@"address":_address,@"name": _name, @"locationX":_latitude, @"locationY":_longitude, @"city":_city,@"district":_district,@"province":_province,@"shotName":_shotName};
        DLog(@"======------黄%@",dic);
        [addressDataArray addObject:dic];
    }else{
        DLog(@"找不到相对应的位置信息");
    }
    
    // 获取坐标周边信息
    int i = 0;
    for(BMKPoiInfo *poiInfo in result.poiList)
    {
        NSDictionary *dic = @{@"address":poiInfo.address, @"name":poiInfo.name, @"locationX":[NSString stringWithFormat:@"%f", poiInfo.pt.latitude], @"locationY":[NSString stringWithFormat:@"%f", poiInfo.pt.longitude], @"city":poiInfo.city};
        [addressDataArray addObject:dic];
        
        i++;
        if (i==result.poiList.count) {
            
            if (!annotaionShow) {
                annotaionShow = YES;
                locationBtn.hidden = NO;
                
                // 地图定位显示
                BMKCoordinateRegion region;
                region.center.latitude  = [_latitude doubleValue];
                region.center.longitude = [_longitude doubleValue];
                region.span.latitudeDelta  = 0;
                region.span.longitudeDelta = 0;
                [UIView animateWithDuration:1 animations:^{
                    mapView.region = region;
                }];
                
                // 一开始显示的(大头针)
                pointAnnotation = [[BMKPointAnnotation alloc]init];
                CLLocationCoordinate2D coor;
                coor.latitude = [_latitude doubleValue];
                coor.longitude = [_longitude doubleValue];
                pointAnnotation.coordinate = coor;
                pointAnnotation.title = _name;
                [mapView addAnnotation:pointAnnotation];
            }
            
            [myTableView reloadData];
        }
    }
}

#pragma mark 地图底部tableView数据展示
- (void)loadAddressTableView {
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, mapView.frame.origin.y+mapView.frame.size.height, XNWindowWidth, XNWindowHeight-mapView.frame.size.height-64) style:UITableViewStylePlain];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
}

// tableviewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (myTableView.contentOffset.y > 0) {
        [tableView setContentOffset:CGPointMake(0,0) animated:YES];
    }
    return addressDataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cellId";
    
    AddMapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AddMapTableViewCell" owner:nil options:nil];
        for (id oneObject in nib) {
            if ([oneObject isKindOfClass:[AddMapTableViewCell class]]) {
                cell = (AddMapTableViewCell *)oneObject;
            }
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.cellImage.image = [UIImage imageNamed:@"定位2.png"];
    
    cell.cellLabelText.text = [addressDataArray[indexPath.row] objectForKey:@"name"];
    cell.cellDetailTextLabelText.text = [addressDataArray[indexPath.row] objectForKey:@"address"];
    
    if (indexPath.row == 0) {
        cell.cellImage.image = [UIImage imageNamed:@"定位1.png"];
        cell.cellLabelText.textColor = [UIColor orangeColor];
        cell.cellDetailTextLabelText.textColor = [UIColor orangeColor];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = addressDataArray[indexPath.row];
    
    _address = [dic objectForKey:@"address"];
    _name = [dic objectForKey:@"name"];
    _city = [dic objectForKey:@"city"];
    _latitude = [dic objectForKey:@"locationX"];
    _longitude = [dic objectForKey:@"locationY"];
    
    [self back];
}

#pragma mark - 返回按钮，并做数据回调处理
- (void)loadBackBtnAndSearchBtn {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 40, 30);
    [btn setImage:[UIImage imageNamed:@"jiantou2"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    //暂时没有搜索框功能,有需要打开注释 搜索框就到位
    
        UIView *titleSearchView = [[UIView alloc] initWithFrame:CGRectMake(20, 5, kScreenWidth-30, 30)];
        titleSearchView.layer.cornerRadius = 5;
        titleSearchView.layer.masksToBounds = YES;
        titleSearchView.layer.borderWidth = 1;
        titleSearchView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        titleSearchView.backgroundColor = [UIColor colorWithRed:235/255.0 green:236/255.0 blue:241/255.0 alpha:1];
        UIImageView *sousuoImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 7, 16, 16)];
        sousuoImage.image = [UIImage imageNamed:@"shouye_sousuo"];
        [titleSearchView addSubview:sousuoImage];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, titleSearchView.frame.size.width-25, 30)];
        label.text = @"查找小区/大厦/学校等";
        label.textColor = [UIColor lightGrayColor];
        label.font = [UIFont systemFontOfSize:14];
        [titleSearchView addSubview:label];
        UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] init];
        [ges addTarget:self action:@selector(searchTextFieldClick)];
        [titleSearchView addGestureRecognizer:ges];
    
        self.navigationItem.titleView = titleSearchView;
    
}
- (void)searchTextFieldClick {
    [self.delegate truneDelgateData];
    TitleSearchViewController *vc = [[TitleSearchViewController alloc] init];
    NSDictionary *dic = @{};
    if (_address!= nil && _latitude!= nil && _longitude!= nil && _city!= nil) {
        if (_name == nil) {
            _name = _address;
        }
        dic = @{@"address":_address,@"name":_name, @"lat":_latitude, @"lon":_longitude, @"city":_city};
    }
 
    DLog(@"%@",dic);
    vc.searchDic = dic;
    vc.titleSearchBlock = ^(NSDictionary *dic) {
        self.addressBlock(dic);
        [self.navigationController popViewControllerAnimated:YES];
    };
    [self.navigationController pushViewController:vc animated:NO];
}

- (void)back {
    if (_address!= nil && _latitude!= nil && _longitude!= nil && _city!= nil) {
        if (_name == nil) {
            _name = _address;
        }
        NSDictionary *dic = @{@"address":_address,@"name":_name, @"lat":_latitude, @"lon":_longitude, @"city":_city,@"district":_district,@"province":_province,@"shotName":_shotName};
        self.addressBlock(dic);
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
